#include <stdio.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
#include <e_file.h>

#define BUFFSIZE	128 
static int cp_file (int rfd, int wfd);

int main (int argc, char **argv)
{
	int pfd[2];
	int fd = 0;
	pid_t pid;
	//创建管道 
	if (-1 == pipe (pfd)) 
	{
		perror ("pipe()");
		return -1;
	}
	pid = fork ();
	if (-1 == pid) {
		perror ("fork()");
		goto ERROR;
	}
	if (0 == pid) {
		//子进程
		close (pfd[1]);
		//读管道，写标准输出
		cp_file (pfd[0], 1);
		close (pfd[0]);
		exit (0);
	} 
	close (pfd[0]);
	fd = open (argv[1], O_RDONLY);
	if (-1 == fd) 
	{
		perror ("open ()");
		close (pfd[1]);
		return -1;
	}
	cp_file (fd, pfd[1]);
	close (pfd[1]);
	close (fd);
	wait (NULL);
	exit (0);
ERROR:
	close (pfd[0]);
	close (pfd[1]);
	exit (1);
}
//cp
static int cp_file (int rfd, int wfd)
{
	char buf[BUFFSIZE] = {0};
	int cnt;
	while (1) {
		memset (buf, '0', BUFFSIZE);
		cnt = read (rfd, buf, BUFFSIZE);
		if (-1 == cnt) {
			perror ("read ()");
			return -1;
		}
		if (0 == cnt) {
			break;
		}
		write (wfd, buf, cnt);
	}
	return 0;
}








